from sqlalchemy import create_engine, Column, String, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from config.app_config import get_app_config
from datetime import datetime
import os
import logging  # 新增日志导入

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 确保元数据目录存在
config = get_app_config()
os.makedirs(config.metadata_db_path.parent, exist_ok=True)

# 数据库连接
engine = create_engine(f"sqlite:///{config.metadata_db_path}")
Base = declarative_base()


# 文档元数据模型
class DocumentMetadata(Base):
    __tablename__ = "document_metadata"
    doc_id = Column(String(64), primary_key=True, comment="文档唯一ID（哈希生成）")
    file_name = Column(String(255), comment="原始文件名")
    file_path = Column(String(512), comment="本地存储路径")
    upload_time = Column(DateTime, default=datetime.now, comment="上传时间")
    chunk_count = Column(Integer, comment="切片数量")
    status = Column(String(20), comment="处理状态：success/failed")


# 创建数据表（首次运行自动创建）
Base.metadata.create_all(engine)


# 数据库操作工具类
class MetadataDB:
    def __init__(self):
        self.Session = sessionmaker(bind=engine)

    def add_document(self, doc_id: str, file_name: str, file_path: str, chunk_count: int, status: str):
        """添加文档元数据"""
        with self.Session() as session:
            doc = DocumentMetadata(
                doc_id=doc_id,
                file_name=file_name,
                file_path=str(file_path),
                chunk_count=chunk_count,
                status=status
            )
            session.add(doc)
            session.commit()

    def get_all_documents(self):
        """获取所有文档元数据（前端展示用）"""
        with self.Session() as session:
            docs = session.query(DocumentMetadata).all()
            return [
                {
                    "doc_id": doc.doc_id,
                    "file_name": doc.file_name,
                    "upload_time": doc.upload_time.strftime("%Y-%m-%d %H:%M:%S"),
                    "chunk_count": doc.chunk_count,
                    "status": doc.status
                }
                for doc in docs
            ]

    def is_document_exist(self, doc_id: str) -> bool:
        """检查文档是否已存在（去重逻辑）"""
        with self.Session() as session:
            return session.query(DocumentMetadata).filter_by(doc_id=doc_id).first() is not None

    # 新增详细日志的删除方法
    def delete_document(self, doc_id: str) -> None:
        """从数据库中删除指定文档的元数据"""
        try:
            logger.info(f"开始删除元数据：{doc_id}（进入delete_document方法）")
            with self.Session() as session:
                # 检查记录是否存在
                doc = session.query(DocumentMetadata).filter_by(doc_id=doc_id).first()
                if not doc:
                    logger.warning(f"元数据不存在：{doc_id}")
                    raise ValueError(f"文档ID {doc_id} 的元数据不存在")

                # 执行删除
                session.query(DocumentMetadata).filter_by(doc_id=doc_id).delete()
                session.commit()
                logger.info(f"元数据删除成功：{doc_id}")
        except Exception as e:
            logger.error(f"元数据删除失败：{str(e)}", exc_info=True)  # 打印完整堆栈
            raise  # 重新抛出异常，让上层处理


# 单例实例（全局复用）
metadata_db = MetadataDB()